<template>
  <div class="aluminum-price-container">
    <h2 class="page-title">铝价数据列表</h2>
    
    <!-- 搜索过滤区域 -->
    <filter-form 
      v-if="!isMobile" 
      :loading="initialLoading"
      :query-params="queryParams"
      @query="handleQuery"
      @reset="resetQuery">
    </filter-form>
    
    <!-- 操作按钮区域 -->
    <action-buttons 
      v-if="!initialLoading"
      :selected-count="selectedRows.length"
      :mobile-view="isMobile"
      @add="handleManualAdd"
      @crawl="showCrawlOptions"
      @batch-delete="handleBatchDelete">
    </action-buttons>
    
    <!-- 数据表格区域 -->
    <transition name="skeleton-fade" mode="out-in">
      <div v-if="loading && !priceList.length" key="skeleton-table">
        <skeleton-table :rows="7" :columns="8" />
      </div>
      <empty-data 
        v-else-if="!loading && priceList.length === 0" 
        key="empty-state"
        @crawl="showCrawlOptions">
      </empty-data>
      <div v-else key="data-table">
        <!-- PC端表格 -->
        <price-table 
          v-if="!isMobile"
          :price-list="priceList"
          :loading="loading"
          :total="total"
          :current-page="queryParams.page"
          :page-size="queryParams.size"
          @selection-change="handleSelectionChange"
          @edit="handleEdit"
          @delete="handleDelete"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </price-table>
        
        <!-- 移动端卡片列表 -->
        <mobile-card-list 
          v-else
          :price-list="priceList"
          :selected-rows="selectedRows"
          @check-change="handleMobileCheck"
          @edit="handleEdit"
          @delete="handleDelete">
        </mobile-card-list>
        
        <!-- 移动端UI组件 -->
        <div class="mobile-ui-wrapper" v-if="isMobile">
          <!-- 移动端批量操作浮动按钮 -->
          <mobile-batch-actions 
            v-if="selectedRows.length > 0"
            :selected-count="selectedRows.length"
            @batch-delete="handleBatchDelete">
          </mobile-batch-actions>
          
          <!-- 移动端筛选器 -->
          <mobile-filter 
            v-if="!initialLoading" 
            v-model="queryParams" 
            :show-filter-tip="showFilterTip"
            @query="handleQuery"
            @reset="fetchData"
            @filter-tip-click="showFilterTip = false">
          </mobile-filter>
        </div>
        
        <!-- 移动端固定分页器 -->
        <mobile-pagination 
          v-if="isMobile && total > 0" 
          :current-page="queryParams.page"
          :page-size="queryParams.size"
          :total="total"
          :page-sizes="[3, 5, 10, 20, 50]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </mobile-pagination>
      </div>
    </transition>
    
    <!-- 爬取选项对话框 -->
    <crawl-dialog 
      :visible="crawlDialogVisible"
      :mobile-view="isMobile"
      :small-mobile-view="isSmallMobile"
      @crawl="handleCrawlOption"
      @update:visible="val => crawlDialogVisible = val">
    </crawl-dialog>
    
    <!-- 新增/编辑对话框 -->
    <price-dialog
      :visible="dialogVisible"
      :title="title"
      :form-data="form"
      :mobile-view="isMobile"
      @submit="submitForm"
      @update:visible="val => dialogVisible = val">
    </price-dialog>

    <!-- 移动端引导提示 -->
    <mobile-guide 
      v-if="isMobile"
      v-model="showGuide"
      :width="$device.width < 500 ? '90%' : '400px'"
      @close="closeGuide">
    </mobile-guide>

    <!-- 全屏加载遮罩 -->
    <div v-if="crawlLoading && isMobile" class="fullscreen-loading">
      <div class="loading-content">
        <i class="el-icon-loading" style="font-size: 32px;"></i>
        <p class="loading-text">正在爬取数据，请稍候...</p>
      </div>
    </div>
  </div>
</template>

<script>
import { aluminumPriceApi } from '@/api/aluminumPrice'
import SkeletonTable from '@/components/SkeletonTable.vue'
import { 
  MobileCardList, 
  MobileBatchActions, 
  MobilePagination, 
  MobileFilter,
  MobileGuide 
} from '@/components/mobile'

import {
  PriceForm,
  PriceTable,
  FilterForm,
  CrawlDialog,
  ActionButtons,
  PriceDialog,
  EmptyData
} from '@/components/aluminum-price'

export default {
  name: 'AluminumPriceList',
  components: {
    SkeletonTable,
    MobileCardList,
    MobileBatchActions,
    MobilePagination,
    MobileFilter,
    MobileGuide,
    PriceForm,
    PriceTable,
    FilterForm,
    CrawlDialog,
    ActionButtons,
    PriceDialog,
    EmptyData
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        startDate: '',
        endDate: '',
        source: '',
        manualUpdate: null
      },
      // 铝价数据列表
      priceList: [],
      // 总数据条数
      total: 0,
      // 加载状态
      loading: false,
      // 爬取数据时的加载状态
      crawlLoading: false,
      // 初始加载状态
      initialLoading: true,
      // 选中数据 - 统一PC和移动端的选择状态
      selectedRows: [],
      // 是否显示对话框
      dialogVisible: false,
      // 对话框标题
      title: '',
      // 表单对象
      form: {
        id: null,
        priceDate: '',
        averagePrice: 0,
        priceSource: ''
      },
      // 爬取对话框可见性
      crawlDialogVisible: false,
      // 显示筛选提示
      showFilterTip: false,
      // 显示使用引导
      showGuide: false
    }
  },
  // 设备检测响应式属性由设备插件自动提供
  created() {
    // 检查是否需要显示引导
    if (typeof window !== 'undefined' && this.isMobile) {
      // 检查本地存储，看是否已经显示过引导
      const hasShownGuide = localStorage.getItem('aluminum_price_guide_shown');
      if (!hasShownGuide) {
        // 延迟显示引导，确保加载完成
        setTimeout(() => {
          this.showGuide = true;
        }, 1000);
      }
    }
    
    this.fetchData()
    
    // 延迟显示筛选提示
    setTimeout(() => {
      this.showFilterTip = this.isMobile;
      
      // 3秒后自动隐藏提示
      if (this.showFilterTip) {
        setTimeout(() => {
          this.showFilterTip = false;
        }, 3000);
      }
    }, 1500);
  },
  methods: {
    // 处理数据加载并设置初始选中状态
    async fetchData() {
      this.loading = true;
      try {
        const response = await aluminumPriceApi.getList({
          page: this.queryParams.page - 1, // 后端页码从0开始
          size: this.queryParams.size,
          startDate: this.queryParams.startDate || null,
          endDate: this.queryParams.endDate || null,
          source: this.queryParams.source || null,
          manualUpdate: this.queryParams.manualUpdate
        });
        
        // 为每个项目添加选中状态属性并保留之前的选择状态
        const priceListWithSelection = response.data.content.map(item => {
          // 检查项目是否在已选中列表中
          const selected = this.selectedRows.some(row => row.id === item.id);
          return { ...item, selected };
        });
        
        this.priceList = priceListWithSelection;
        this.total = response.data.totalElements;
      } catch (error) {
        // 区分后端错误和前端错误
        if (error.response) {
          // 后端返回的错误信息
          this.$message.error(error.response.data.message || '获取数据失败');
        } else {
          // 前端自身的错误
          this.$message.error('获取数据失败：' + error.message);
        }
      } finally {
        this.loading = false;
        this.initialLoading = false;
      }
    },
    
    // 搜索按钮点击
    handleQuery(queryData) {
      if (queryData) {
        this.queryParams = {
          ...this.queryParams,
          ...queryData,
          page: 1
        };
      } else {
        this.queryParams.page = 1;
      }
      this.fetchData();
    },
    
    // 重置按钮点击
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        startDate: '',
        endDate: '',
        source: '',
        manualUpdate: null
      }
      this.fetchData()
    },
    
    // 表格多选变化 - 统一选择逻辑
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      
      // 同步更新列表项的选中状态
      this.updateSelectionState();
    },
    
    // 移动端单选处理 - 统一选择逻辑
    handleMobileCheck({ checked, row }) {
      if (checked) {
        // 避免重复添加
        if (!this.selectedRows.some(item => item.id === row.id)) {
          this.selectedRows.push(row);
        }
      } else {
        // 移除已取消选中的项
        this.selectedRows = this.selectedRows.filter(item => item.id !== row.id);
      }
      
      // 同步更新列表项的选中状态
      this.updateSelectionState();
    },
    
    // 更新列表项的选中状态
    updateSelectionState() {
      // 将选中状态同步到列表中
      if (this.priceList && this.priceList.length) {
        this.priceList.forEach(item => {
          item.selected = this.selectedRows.some(row => row.id === item.id);
        });
      }
    },
    
    // 页码变化处理
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.fetchData();
      // 滚动到顶部，提升用户体验
      if (typeof window !== 'undefined') {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    },
    
    // 页面大小变化处理
    handleSizeChange(size) {
      this.queryParams.size = size;
      // 切换每页记录数时重置为第一页
      this.queryParams.page = 1;
      this.fetchData();
      // 滚动到顶部
      if (typeof window !== 'undefined') {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    },
    
    // 手动添加按钮点击
    handleManualAdd() {
      this.title = '添加铝价数据'
      this.form = {
        id: null,
        priceDate: new Date().toISOString().split('T')[0],
        averagePrice: 0,
        priceSource: 'shanghai'
      }
      this.dialogVisible = true
    },
    
    // 编辑按钮点击
    handleEdit(row) {
      this.title = '编辑铝价数据'
      this.form = {
        id: row.id,
        priceDate: row.priceDate,
        averagePrice: row.averagePrice,
        priceSource: row.priceSource
      }
      this.dialogVisible = true
    },
    
    // 删除按钮点击
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该条铝价数据吗?', '提示', {
          type: 'warning'
        })
        
        try {
          const res = await aluminumPriceApi.delete(row.id)
          if (res.data.success) {
            this.$message.success('删除成功')
            this.fetchData()
          } else {
            this.$message.error(res.data.message || '删除失败')
          }
        } catch (error) {
          // 区分后端错误和前端错误
          if (error.response) {
            // 后端返回的错误信息
            this.$message.error(error.response.data.message || '删除失败');
          } else {
            // 前端自身的错误
            this.$message.error('删除失败：' + error.message);
          }
        }
      } catch (cancelError) {
        // 用户取消操作，不做处理
      }
    },
    
    // 批量删除后清空选中状态
    clearSelections() {
      this.selectedRows = [];
      
      // 清除每个项目的选中状态
      if (this.priceList && this.priceList.length) {
        this.priceList.forEach(item => {
          item.selected = false;
        });
      }
    },
    
    // 批量删除
    async handleBatchDelete() {
      const ids = this.selectedRows.map(row => row.id);
      if (ids.length === 0) {
        this.$message.warning('请至少选择一条数据');
        return;
      }
      
      try {
        await this.$confirm(`确认批量删除这${ids.length}条铝价数据吗?`, '提示', {
          type: 'warning'
        });
        
        this.loading = true;
        try {
          const res = await aluminumPriceApi.batchDelete(ids);
          if (res.data.success) {
            this.$message.success('批量删除成功');
            // 清空选中数组
            this.clearSelections();
            this.fetchData();
          } else {
            this.$message.error(res.data.message || '批量删除失败');
          }
        } catch (error) {
          // 区分后端错误和前端错误
          if (error.response) {
            // 后端返回的错误信息
            this.$message.error(error.response.data.message || '批量删除失败');
          } else {
            // 前端自身的错误
            this.$message.error('批量删除失败：' + error.message);
          }
        } finally {
          this.loading = false;
        }
      } catch (cancelError) {
        // 用户取消操作，不做处理
      }
    },
    
    // 表单提交
    async submitForm(formData) {
      const { priceSource, averagePrice, priceDate } = formData;
      try {
        const res = await aluminumPriceApi.updatePrice(priceSource, averagePrice, priceDate);
        if (res.data.success) {
          this.$message.success('保存成功');
          this.dialogVisible = false;
          this.fetchData();
        } else {
          this.$message.error(res.data.message || '保存失败');
        }
      } catch (error) {
        // 区分后端错误和前端错误
        if (error.response) {
          // 后端返回的错误信息
          this.$message.error(error.response.data.message || '保存失败');
        } else {
          // 前端自身的错误
          this.$message.error('保存失败：' + error.message);
        }
      }
    },
    
    // 显示爬取选项
    showCrawlOptions() {
      this.crawlDialogVisible = true;
    },
    
    // 处理爬取选项
    async handleCrawlOption(source) {
      this.crawlDialogVisible = false;
      if (source === 'shanghai') {
        await this.crawlShanghai();
      } else if (source === 'changjiang') {
        await this.crawlChangjiang();
      }
    },
    
    // 爬取上海铝价
    async crawlShanghai() {
      try {
        await this.$confirm('确认爬取今日上海铝价数据?', '提示', {
          type: 'info'
        });
        
        // 设置加载状态
        this.loading = true;
        if (this.isMobile) {
          this.crawlLoading = true;
        }
        
        try {
          const res = await aluminumPriceApi.crawlShanghai();
          if (res.data.success) {
            this.$message.success('上海铝价爬取成功');
            this.fetchData();
          } else {
            this.$message.error(res.data.message || '上海铝价爬取失败');
          }
        } catch (error) {
          // 区分后端错误和前端错误
          if (error.response) {
            // 后端返回的错误信息
            this.$message.error(error.response.data.message || '爬取失败');
          } else {
            // 前端自身的错误
            this.$message.error('爬取失败：' + error.message);
          }
        } finally {
          this.loading = false;
          if (this.isMobile) {
            this.crawlLoading = false;
          }
        }
      } catch (cancelError) {
        // 用户取消操作，不做处理
      }
    },
    
    // 爬取长江铝价
    async crawlChangjiang() {
      try {
        await this.$confirm('确认爬取今日长江铝价数据?', '提示', {
          type: 'info'
        });
        
        // 设置加载状态
        this.loading = true;
        if (this.isMobile) {
          this.crawlLoading = true;
        }
        
        try {
          const res = await aluminumPriceApi.crawlChangjiang();
          if (res.data.success) {
            this.$message.success('长江铝价爬取成功');
            this.fetchData();
          } else {
            this.$message.error(res.data.message || '长江铝价爬取失败');
          }
        } catch (error) {
          // 区分后端错误和前端错误
          if (error.response) {
            // 后端返回的错误信息
            this.$message.error(error.response.data.message || '爬取失败');
          } else {
            // 前端自身的错误
            this.$message.error('爬取失败：' + error.message);
          }
        } finally {
          this.loading = false;
          if (this.isMobile) {
            this.crawlLoading = false;
          }
        }
      } catch (cancelError) {
        // 用户取消操作，不做处理
      }
    },
    
    // 关闭引导对话框
    closeGuide(doNotShowAgain) {
      // 如果选中了不再显示，记录到本地存储
      if (doNotShowAgain && typeof localStorage !== 'undefined') {
        localStorage.setItem('aluminum_price_guide_shown', 'true');
      }
    }
  }
}
</script>

<style scoped>
.fullscreen-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.loading-text {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}
</style>